<template>
  <div>
    <template v-if="type === 'radio'">
      <el-radio-group v-model="currentValue">
        <el-radio v-for="item of ($store.state.common.dictData[dictType] || dataList)" :key="item.id" :label="item.code">{{ item.dictValue }}</el-radio>
      </el-radio-group>
    </template>
    <template v-else-if="type === 'checkbox'">
      <el-checkbox-group v-model="currentValue" >
        <el-checkbox v-for="item of ($store.state.common.dictData[dictType] || dataList)" :key="item.id" :label="item.dictValue" :true-label="item.code" />
      </el-checkbox-group>
    </template>
    <template v-else>
      <el-select clearable v-model="currentValue" placeholder="请选择">
        <el-option v-for="item of ($store.state.common.dictData[dictType] || dataList)" :key="item.id" :label="item.dictValue" :value="item.code" />
      </el-select>
    </template>
  </div>
</template>

<script>
import { getDict } from '@/api/sys/dict'
import { mapState } from 'vuex'
export default {
  props: {
    type: {
      type: String,
      default: 'select',
      validator(value) {
        return ['select', 'radio', 'checkbox'].indexOf(value) !== -1
      }
    },
    dictType: {
      type: [String, Number],
      required: true
    },
    value: {
      required: true
    }
  },
  data() {
    return {
      dataList: []
    }
  },
  computed: {
    ...mapState('common', ['dictData']),
    currentValue: {
      get() {
        return this.value !== undefined ? this.value.toString() : ''
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  mounted() {
    const key = this.dictType
    if (!this.dictData[key]) {
      getDict(key).then((res) => {
        const data = res.obj
        // 改变vuex状态
        this.$store.commit('common/SET_DICTDATA', { key, data })
        this.dataList = data
      })
    }
  }
}
</script>
